package com.mytest.myID;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RedisID {
    private static volatile JedisPool jedisPool = null;

    private RedisID() {
    }

    public static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            synchronized (RedisID.class) {
                if (null == jedisPool) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(1000);
                    poolConfig.setMaxIdle(32);
                    poolConfig.setMaxWaitMillis(100 * 1000);
                    poolConfig.setTestOnBorrow(true);

                    jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379);
                }
            }
        }
        return jedisPool;
    }

    public static void release(JedisPool jedisPool, Jedis jedis) {
        if (null != jedis) {
            Jedis jedis2 = null;
            try {
                jedis2 = jedisPool.getResource();
            } finally {
                jedis2.close();
            }
        }
    }

    public static String getRedisID(Jedis jedis) {
        jedis.incr("id");
        return jedis.get("id");
    }

    public static void main(String[] args) throws InterruptedException {
        JedisPool jedisPool = RedisID.getJedisPoolInstance();
        Jedis jedis = null;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor
                (3, 8, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));

        for (int i = 0; i < 10; i++) {
            if (threadPoolExecutor.getActiveCount() <= 8) {
                threadPoolExecutor.execute(() -> {
                    try {
                        System.out.println(getRedisID(jedisPool.getResource()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        RedisID.release(jedisPool, jedis);
                    }
                });
            }
        }
        TimeUnit.SECONDS.sleep(2);
        threadPoolExecutor.shutdown();
    }
}
